<?php

namespace App\Models;

use App\Models\Common\Common;
use App\Models\Tools\AliOss;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Work
{

    /**
     * 查询探店订单对应的工单信息
     * @param int $eo_id 订单id
     * @param array $status 工单状态
     * @return array
     */
    public static function orderWorks(int $eo_id, array $status = []): array
    {
        $where = function ($query) use ($eo_id, $status) {
            $query->where('ew.eo_id', '=', $eo_id);
            if (count($status)) {
                $query->whereIn('ew.status', $status);
            }
        };
        $works = DB::table('explore_work as ew')
            ->leftJoin('talent', 'ew.talent_id', '=', 'talent.talent_id')
            ->leftJoin('lottery_users as lu', 'ew.receiver_we_id', '=', 'lu.we_id')
            ->where($where)
            ->select('ew.work_id', 'ew.work_no', 'ew.status', 'ew.receive_time', 'ew.receiver_we_id', 'ew.talent_id', 'lu.nickname', 'lu.phone', 'talent.account_name')
            ->get()
            ->map(function ($item) {
                $item->status_name = Data::$exploreWorkStatus[$item->status];
                return $item;
            })
            ->toArray();
        $works = json_decode(json_encode($works), true);
        return $works;

    }

    /**
     * 处理工单状态
     * @param int $status 工单状态
     * @param int $error_reason 异常原因
     * @return array
     */
    public static function workSteps($status, $error_reason)
    {
        $result = [];
        switch ($status) {
            case Data::DATA_DB_EXPLORE_WORK_STATUS_INIT:
            case Data::DATA_DB_EXPLORE_WORK_STATUS_SUBMIT:
            case Data::DATA_DB_EXPLORE_WORK_STATUS_ACCEPTED:
            case Data::DATA_DB_EXPLORE_WORK_STATUS_CHECK:
            case Data::DATA_DB_EXPLORE_WORK_STATUS_SETTLEMENT:
                $result = [
                    'steps' => ['已接单', '已投稿', '已验收', '待结算', '已结算'],
                    'current_step' => $status,
                    'err_msg' => '',
                ];
                break;
            case Data::DATA_DB_EXPLORE_WORK_STATUS_REFUSE:
                $result = [
                    'steps' => ['已接单', '已投稿', '已验收', '待结算', '已结算'],
                    'current_step' => 2,
                    'err_msg' => Data::$exploreWorkStatus[Data::DATA_DB_EXPLORE_WORK_STATUS_REFUSE],
                ];
                break;
            case Data::DATA_DB_EXPLORE_WORK_STATUS_ERROR:
                $result = [
                    'steps' => [],
                    'current_step' => null,
                    'err_msg' => Data::$exploreWorkErrorReason[$error_reason],
                ];
                break;
        }
        return $result;

    }

    /**
     * 订单：查询订单信息
     * @param int $eo_id
     * @return array
     */
    public static function orderMessage(int $eo_id): array
    {
        $order = DB::table('explore_order')->where('eo_id', '=', $eo_id)->first();
        $order = json_decode(json_encode($order), true);
        if ($order['start_date'] === $order['end_date']) {
            $order['explore_date'] = $order['start_date'];
        } else {
            $order['explore_date'] = $order['start_date'] . '~' . $order['end_date'];
        }
        $order['channel_name'] = DB::table('explore_channel')->where('channel_id', '=', $order['channel_id'])->value('channel_name');
        $order['status_name'] = Data::$exploreOrderStatus[$order['status']];
        $order['shop_img'] = AliOss::getUrls(explode(',', $order['shop_img']));
        return $order;
    }

    /**
     * 工单：查询工单信息
     * @param int $work_id 工单id
     * @return array
     */
    public static function workMessage(int $work_id): array
    {
        $work = DB::table('explore_work')->where('work_id', '=', $work_id)->first();
        $work = json_decode(json_encode($work), true);
        $work['status_name'] = Data::$exploreWorkStatus[$work['status']];
        if ($work['error_reason']) {
            $work['error_reason_name'] = Data::$exploreWorkErrorReason[$work['error_reason']];
        }
        if ($work['accept_user']) {
            $work['accept_user_name'] = DB::table('lottery_users')->where('we_id', '=', $work['accept_user'])->value('nickname');
        }
        if ($work['settlement_user']) {
            $work['settlement_user_name'] = DB::table('users')->where('id', '=', $work['settlement_user'])->value('name');
        }
        if ($work['submit_img']) {
            $work['submit_img'] = AliOss::getUrl($work['submit_img']);
        }
        if ($work['clock_in_img']) {
            $work['clock_in_img'] = AliOss::getUrl($work['clock_in_img']);
        }
        $work['step'] = self::workSteps($work['status'], $work['error_reason']);
        $work['payment'] = $work['settlement_amount']/100.00;
        // 查询申诉信息
        $work['hang_up'] = self::hangUpMessage($work_id);
        return $work;
    }

    /**
     * 工单：查询店铺信息
     * @param int $shop_id 店铺id
     * @return array
     */
    public static function shopMessage(int $shop_id): array
    {
        $shop = DB::table('shop')
            ->leftJoin('dict_area as da', 'shop.district', '=', 'da.id')
            ->leftJoin('lottery_users as lu', 'shop.we_id', '=', 'lu.we_id')
            ->where('shop.shop_id', '=', $shop_id)
            ->select('shop.shop_id', 'shop.we_id', 'shop.shop_name', 'shop.contact_man', 'shop.contact_phone', 'shop.province', 'shop.city', 'shop.district',
                'shop.address','shop.link_url', 'da.short_name', 'lu.openid', 'lu.nickname', 'lu.phone')
            ->first();
        $shop = json_decode(json_encode($shop), true);
        return $shop;
    }

    /**
     * 工单：查询达人信息
     * @param int $talent_id 达人id
     * @return array
     */
    public static function receiverMessage(int $talent_id): array
    {
        $receiver = DB::table('talent')
            ->leftJoin('lottery_users as lu', 'talent.we_id', '=', 'lu.we_id')
            ->where('talent.talent_id', '=', $talent_id)
            ->select('talent.account_name', 'lu.we_id', 'lu.openid', 'lu.nickname', 'lu.phone')
            ->first();
        $receiver = json_decode(json_encode($receiver), true);
        return $receiver;
    }

    /**
     * 查询工单日志
     * @param int $work_id 工单id
     * @param bool $public 是否是公开日志（公开日志不查remark）
     * @return array
     */
    public static function workLog(int $work_id, bool $public = true): array
    {
        if ($public) {
            $logs = DB::table('explore_work_log as ewl')
                ->leftJoin('lottery_users as lu', 'ewl.we_id', '=', 'lu.we_id')
                ->leftJoin('users', 'ewl.user_id', '=', 'users.id')
                ->where('ewl.work_id', '=', $work_id)
                ->select('ewl.log_id', 'ewl.action', 'ewl.we_id', 'ewl.user_id', 'ewl.created_at','ewl.remark',
                    'lu.nickname', 'users.name')
                ->orderByDesc('ewl.log_id')
                ->get()
                ->map(function ($item) {
                    if(!in_array($item->action,[Data::DATA_DB_EXPLORE_WORK_ACTION_OVERTIME,Data::DATA_DB_EXPLORE_WORK_ACTION_CANCEL])){
                        $remark = '';
                        if ($item->nickname) {
                            $remark = '用户【' . $item->nickname . '】: ';
                        }
                        if ($item->name) {
                            $remark = '管理员【' . $item->name . '】: ';
                        }
                        $remark .= Data::$exploreWorkAction[$item->action];
                        $item->remark = $remark;
                    }
                    return $item;
                })
                ->toArray();
        } else {
            $logs = DB::table('explore_work_log')
                ->where('work_id', '=', $work_id)
                ->select('log_id', 'action', 'we_id', 'user_id', 'remark', 'created_at')
                ->orderByDesc('log_id')
                ->get()
                ->toArray();
        }
        $logs = json_decode(json_encode($logs), true);
        return $logs;
    }

    /**
     * 订单日志
     * @param int $eo_id 订单id
     * @return array
     */
    public static function orderLog(int $eo_id): array
    {
        $logs = DB::table('explore_order_log as eol')
            ->leftJoin('lottery_users as lu', 'eol.we_id', '=', 'lu.we_id')
            ->leftJoin('users', 'eol.user_id', '=', 'users.id')
            ->where('eol.eo_id', '=', $eo_id)
            ->select('eol.log_id', 'eol.action', 'eol.we_id', 'eol.user_id', 'eol.created_at',
                'lu.nickname', 'users.name')
            ->orderByDesc('log_id')
            ->get()
            ->map(function ($item) {
                $item->action_name = Data::$exploreOrderAction[$item->action];
                $remark = '';
                if ($item->nickname) {
                    $remark = '用户【' . $item->nickname . '】: ';
                }
                if ($item->name) {
                    $remark = '管理员【' . $item->name . '】: ';
                }
                $remark .= $item->action_name;
                $item->remark = $remark;
                return $item;
            })
            ->toArray();

        $logs = json_decode(json_encode($logs), true);
        return $logs;
    }

    /**
     * 查询工单信息并锁表（需在事务中使用）
     * @param int $work_id
     * @return array
     */
    public static function exploreWorkAndX(int $work_id): array
    {
        $work = DB::table('explore_work')
            ->where('work_id', '=', $work_id)
            ->lockForUpdate()
            ->first();
        return json_decode(json_encode($work), true);
    }

    /**
     * 查询订单信息并锁表（需在事务中使用）
     * @param int $eo_id
     * @return array
     */
    public static function exploreOrderAndX(int $eo_id): array
    {
        $order = DB::table('explore_order')
            ->where('eo_id', '=', $eo_id)
            ->lockForUpdate()
            ->first();
        return json_decode(json_encode($order), true);
    }

    /**
     * 查询余量信息并锁表（需在事务中使用）
     * @param int $we_id
     * @param int $channel_id
     * @return array
     */
    public static function exploreRemainingAndX(int $we_id, int $channel_id): array
    {
        $remaining = DB::table('explore_remaining')
            ->where('we_id', '=', $we_id)
            ->where('channel_id', '=', $channel_id)
            ->lockForUpdate()
            ->first();
        return json_decode(json_encode($remaining), true);
    }


    /**
     * 取消订单后操作订单数量修改（需在事务中使用）
     * @param array $order explore_order.row
     */
    public static function workCancelToOrder($order)
    {
        // 修改订单状态
        $order_update = [
            'pending_num' => $order['pending_num'] - 1,
            'failed_num' => $order['failed_num'] + 1,
        ];
        // 订单内的全部工单已执行完毕，订单完成
        if ($order['pending_num'] === 1) {
            $order_update['status'] = Data::DATA_DB_EXPLORE_ORDER_STATUS_FINISHED;
            // 修改订单状态并记录日志
            DB::table('explore_order')
                ->where('eo_id','=',$order['eo_id'])
                ->update($order_update);
            DB::table('explore_order_log')->insert([
                'eo_id' => $order['eo_id'],
                'action' => Data::DATA_DB_EXPLORE_ORDER_ACTION_FINISHED,
            ]);
        } else {
            // 修改订单数量
            DB::table('explore_order')
                ->where('eo_id','=',$order['eo_id'])
                ->update($order_update);
        }
    }

    /**
     * 取消订单后操作发单者剩余数量修改（需在事务中使用）
     * @param array $remaining explore_remaining.row
     */
    public static function workCancelToRemaining($remaining)
    {
        // 修改发单者剩余数量并记录日志
        DB::table('explore_remaining')->where('r_id', '=', $remaining['r_id'])->update([
            'remaining_times' => $remaining['remaining_times'] + 1,
            'in_use_times' => $remaining['in_use_times'] - 1,
        ]);
        DB::table('explore_remaining_log')->insert([
            'r_id' => $remaining['r_id'],
            'action' => Data::DATA_DB_EXPLORE_REMAINING_LOG_TYPE_WORK_CANCEL,//工单取消退回
            'action_num' => 1,
            'rest_num' => $remaining['remaining_times'] + 1,
            'in_use_num' => $remaining['in_use_times'] - 1,
        ]);
    }

    public static function hangUpMessage($work_id)
    {
        // 查询申诉信息
        return DB::table('explore_hang_up')
            ->where('work_id','=',$work_id)
            ->orderByDesc('created_at')
            ->get()
            ->map(function($item){
                switch ($item->feedback){
                    case 1:
                        $item->feedback_name = '申诉失败';
                        break;
                    case 2:
                        $item->feedback_name = '申诉成功';
                        break;
                    default:
                        $item->feedback_name = '待处理';
                }
                return $item;
            })
            ->toArray();

    }


}
